package com.kczd.jinlan.view.shouye.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.kczd.jinlan.R;
import com.kczd.jinlan.adapter.TejiaAdapter;
import com.kczd.jinlan.adapter.normaladapter.ClassifyAdapter;
import com.kczd.jinlan.model.Classify;
import com.kczd.jinlan.model.Goods;
import com.kczd.jinlan.myview.FullyGridLayoutManager;
import com.kczd.jinlan.myview.MenuPopwindow;
import com.kczd.jinlan.myview.NoScrollGridView;
import com.kczd.jinlan.myview.PicsView;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.utils.StringUtils;
import com.kczd.jinlan.view.shouye.DetailsFoodActivity;
import com.kczd.jinlan.view.shouye.classActivity.ClassifydetilActivity;
import com.kczd.jinlan.view.shouye.searchActivity.SearchAreaActivity;
import com.kczd.jinlan.view.shouye.searchActivity.SearchClassifyActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;
import static com.kczd.jinlan.R.id.picsviewpager;

/**
 * yang_g
 * 商城模块
 * Created by Administrator on 2017/5/15.
 */

public class ShangchengFragment extends Fragment implements View.OnClickListener {

    private static final String TAG="ShangchengFragment.class";
    String[] titles = {"我", "爱", "金", "兰", "蔬", "菜"};
    String url = Config.net_addr + "index/index";
    int[] imgs = {R.mipmap.shouye_lunbo, R.mipmap.shouye_lunbo, R.mipmap.shouye_lunbo, R.mipmap.shouye_lunbo, R.mipmap.shouye_lunbo,
            R.mipmap.shouye_lunbo};

    private View view;
    private PicsView mPicsviewpager;
    private NoScrollGridView mGridView;
    private RecyclerView recyclerView;
    private EditText mEdit;
    private TextView mArea;
    private TextView mTejiatuijian;

    private AMapLocationClient mLocationClient;

    public static List<Classify> minelist;
    public static List<Goods> telist;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.shopping_fragment, null);
        initViewPager();
        initData();
        initView();
        initLocation();
        return view;
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getActivity());
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        Log.e("onLocationChanged", "city: " + city);
                        Log.e("onLocationChanged", "district: " + district);
                        String location = StringUtils.extractLocation(city, district);
                        mArea.setText(location);
                        mArea.setTextColor(Color.WHITE);
                    } else {
                        //定位失败
                        mArea.setText("乌鲁木齐");
                        mArea.setTextColor(Color.WHITE);
                    }
                }
            }
        });
        mLocationClient.startLocation();
    }

    private void initView() {
        mEdit = (EditText) view.findViewById(R.id.et_search);//搜索
        mEdit.setOnClickListener(this);
        mArea = (TextView) view.findViewById(R.id.id_area);//选择区域
        mArea.setOnClickListener(this);
        view.findViewById(R.id.id_xiaoxi).setOnClickListener(this);
        mTejiatuijian = (TextView) view.findViewById(R.id.id_tejiatuijian);
        mTejiatuijian.setCompoundDrawablePadding(6);//修改drawable与文字的间距是6
        view.findViewById(R.id.id_more).setOnClickListener(this);
    }

    private void initReView() {
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        FullyGridLayoutManager linearLayoutManager = new FullyGridLayoutManager(getActivity(), 2);
        recyclerView.setNestedScrollingEnabled(false);
        //设置布局管理器
        recyclerView.setLayoutManager(linearLayoutManager);

        TejiaAdapter tejia = new TejiaAdapter(getActivity(), telist);

        /**
         * 特价推荐跳转页面
         */
        tejia.setOnItemClickLitener(new TejiaAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {

                Intent intent=new Intent(getActivity(), DetailsFoodActivity.class);
                Bundle bundle=new Bundle();
                bundle.putInt("position",position);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
        recyclerView.setAdapter(tejia);
    }

    private void initData() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                getIndex();
            }
        }).start();
    }

    public void getIndex(){
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder().build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))){
                    JSONObject jb= jsonResult.getJSONObject("data");
                    JSONArray js=jb.getJSONArray("category");
                    JSONArray js1=jb.getJSONArray("goods_list");
                    minelist = new ArrayList<Classify>();
                    telist=new ArrayList<>();
                    for(int i=0;i<js.length();i++)
                    {
                        Classify classify=new Classify();
                        JSONObject jbi=js.getJSONObject(i);
                        classify.setId(jbi.getString("id"));
                        classify.setImage(jbi.getString("image"));
                        classify.setName(jbi.getString("name"));
                        classify.setMobile_name(jbi.getString("mobile_name"));
                        classify.setParent_id(jbi.getString("parent_id"));
                        classify.setParent_id_path(jbi.getString("parent_id_path"));
                        classify.setLevel(jbi.getString("level"));
                        classify.setSort_order(jbi.getString("sort_order"));
                        classify.setIs_show(jbi.getString("is_show"));
                        classify.setIs_hot(jbi.getString("is_hot"));
                        classify.setCat_group(jbi.getString("cat_group"));
                        minelist.add(classify);
                    }
//                    minelist.add(new Classify("特价区",""));
//                    minelist.add(new Classify("积分商城",""));
//                    minelist.add(new Classify("畅销区",""));
                    for(int j=0;j<js1.length();j++)
                    {
                        Goods goods=new Goods();
                        JSONObject jbgoods=js1.getJSONObject(j);
                        goods.setTitle(jbgoods.getString("goods_name"));
                        goods.setPrice(jbgoods.getString("market_price"));
                        goods.setOldprice(jbgoods.getString("cost_price"));
                        goods.setCid(jbgoods.getString("goods_id"));
                        goods.setWeight_dai(jbgoods.getString("weight"));//商品每袋重量
                        goods.setPrice_kg(jbgoods.getString("shop_price"));//商品每千克的价钱
                        goods.setImage(jbgoods.getString("original_img"));
                        goods.setCount(1);
                        telist.add(goods);
                    }

                    initReView();

                    mGridView = (NoScrollGridView) view.findViewById(R.id.me_item_gridview);
                    mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
                    ClassifyAdapter mineActivity = new ClassifyAdapter(minelist);
                    mGridView.setAdapter(mineActivity);
                    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "Position:" + position);
                Intent intent = new Intent(getActivity(), ClassifydetilActivity.class);
                intent.putExtra("claseeify_position",position+"");
                startActivity(intent);
            }
        });
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };



    private void initViewPager() {
        mPicsviewpager = (PicsView) view.findViewById(picsviewpager);

        List<ImageView> imgList = new ArrayList<ImageView>();
        for (int i = 0; i < imgs.length; i++) {
            ImageView iv = new ImageView(getActivity());
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setImageResource(imgs[i]);
            imgList.add(iv);
        }
        // 初始化数据
        mPicsviewpager.setTitlesAndImages(titles, imgList);

        // 设置点击事件
        mPicsviewpager.setOnLunBoClickListener(new PicsView.OnLunBoClickListener() {

            @Override
            public void clickLunbo(int position) {
                System.out.println("点击有效");
                Toast.makeText(getActivity(), "点击有效，位置为：" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onPause() {
        // 停止图片轮播
        mPicsviewpager.stopAutoScroll();
        super.onPause();
    }

    @Override
    public void onResume() {
        // 开启图片轮播
        mPicsviewpager.startAutoScroll();
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_search://跳转到搜寻页面
                startActivity(new Intent(getActivity(), SearchClassifyActivity.class));
                break;
            case R.id.id_area://跳转到搜寻地址页面
                Intent intent = new Intent(getActivity(), SearchAreaActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.id_xiaoxi://右上角的actionbar
                MenuPopwindow popWindow = new MenuPopwindow(getActivity());
                popWindow.showPopupWindow(view.findViewById(R.id.id_xiaoxi));
                break;
            case R.id.id_more://更多按钮
                Intent intents = new Intent(getActivity(), ClassifydetilActivity.class);
                intents.putExtra("tobar", "特价推荐");
                startActivity(intents);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    String returnedData = data.getStringExtra(SearchAreaActivity.KEY_PICKED_CITY);
                    mArea.setText(returnedData);
                }
                break;
        }
    }

}
